package com.hutao.medical.service.print;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.im4java.core.IM4JavaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.hutao.medical.common.config.ConfigProperties;
import com.hutao.medical.common.util.DateUtil;
import com.hutao.medical.common.util.GraphicsMagicUtil;
import com.hutao.medical.common.util.HttpClientUtil;
import com.hutao.medical.common.util.JsonUtils;
import com.hutao.medical.common.util.Params;
import com.hutao.medical.common.util.Result;
import com.hutao.medical.common.util.StringUtil;
import com.hutao.medical.common.util.TmFileUtil;
import com.hutao.medical.constant.FunctionType;
import com.hutao.medical.dataSource.TargetDataSource;
import com.hutao.medical.mapper.MailRegistraionMapper;
import com.hutao.medical.mapper.print.ApplyPrintDetailMapper;
import com.hutao.medical.mapper.print.ApplyPrintMapper;
import com.hutao.medical.mapper.print.HospitalNoteMapper;
import com.hutao.medical.mapper.print.MedicalFunctionMapper;
import com.hutao.medical.mapper.print.MedicalMailMapper;
import com.hutao.medical.mapper.print.MedicalPrintMapper;
import com.hutao.medical.mapper.print.PrintApplyImageMapper;
import com.hutao.medical.mapper.print.PrintDetailMapper;
import com.hutao.medical.mapper.print.PrintFeeDetailMapper;
import com.hutao.medical.mapper.print.PrintFeeMapper;
import com.hutao.medical.mapper.print.PrintMailRecordMapper;
import com.hutao.medical.mapper.print.PrintMapper;
import com.hutao.medical.mapper.print.PrintRecordMapper;
import com.hutao.medical.pojo.MailRegistraion;
import com.hutao.medical.pojo.dto.PrintPageDto;
import com.hutao.medical.pojo.print.ApplyPrint;
import com.hutao.medical.pojo.print.ApplyPrintDetail;
import com.hutao.medical.pojo.print.HospitalNote;
import com.hutao.medical.pojo.print.MedicalFunction;
import com.hutao.medical.pojo.print.MedicalMail;
import com.hutao.medical.pojo.print.MedicalPrint;
import com.hutao.medical.pojo.print.Print;
import com.hutao.medical.pojo.print.PrintApplyImage;
import com.hutao.medical.pojo.print.PrintDetail;
import com.hutao.medical.pojo.print.PrintFee;
import com.hutao.medical.pojo.print.PrintFeeDetail;
import com.hutao.medical.pojo.print.PrintFeeExample;
import com.hutao.medical.pojo.print.PrintMailRecord;
import com.hutao.medical.pojo.print.PrintRecord;
import com.hutao.medical.pojo.vo.ApplyPrintVo;
import com.hutao.medical.pojo.vo.PrintCheckVo;
import com.hutao.medical.pojo.vo.PrintRecordVo;
import com.hutao.medical.pojo.vo.PrintSaoMiao;
@Transactional
@Service
public class ApplyPrintService {
	
	@Autowired
	private ApplyPrintMapper applyPrintMapper;
	
	
	@Autowired
	private ApplyPrintDetailMapper applyPrintDetailMapper;
	
	@Autowired
	private PrintMapper printMapper;
	
	@Autowired
	private PrintFeeMapper printFeeMapper;
	
	@Autowired
	private HospitalNoteMapper hospitalNoteMapper;
	
	@Autowired
	private PrintFeeDetailMapper printFeeDetailMapper;
	
	@Autowired
	private MailRegistraionMapper mailRegistraionMapper;
	
	@Autowired
	private PrintDetailMapper printDetailMapper;
	
	@Autowired
	private ConfigProperties configProperties;
	
	@Autowired
	private PrintRecordMapper printRecordMapper;
	
	@Autowired
	private PrintMailRecordMapper printMailRecordMapper;
	
	@Autowired
	private MedicalFunctionMapper medicalFunctionMapper;
	
	@Autowired
	private MedicalPrintMapper medicalPrintMapper;
	
	@Autowired
	private PrintApplyImageMapper printApplyImageMapper;
	
	@Autowired
	private MedicalMailMapper medicalMailMapper;
	

	@Transactional(propagation=Propagation.REQUIRED)
	public int addApplyPrint(ApplyPrint applyPrint){
		return applyPrintMapper.insert(applyPrint);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public int print(ApplyPrint applyPrint,ApplyPrintVo applyPrintVo){

		//添加打印申请信息
		applyPrint.setApplyDate(applyPrint.getApplyDate()!=null?applyPrint.getApplyDate():new Date());
		applyPrintMapper.insertSelective(applyPrint);
		
		//添加打印信息
		Print print=new Print();
		print.setUniqueId(applyPrint.getUniqueId());
		print.setApplyName(applyPrint.getApplyName());
		print.setApplyCard(applyPrint.getApplyCard());
		print.setApplyData(applyPrint.getApplyDate());
		print.setApplyReason(applyPrint.getApplyReason());
		print.setComment(applyPrint.getComment());
		printMapper.insert(print);
		
		PrintFee printFee=new PrintFee();
		printFee.setUniqueId(applyPrint.getUniqueId());
		printFee.setApplyName(applyPrint.getApplyName());
		printFee.setApplyCard(applyPrint.getApplyCard());
		printFee.setPerPagePrice(0.5f);
		//printFee.setPerchargeCount(prePrintFee!=null && prePrintFee!=""?Float.parseFloat(prePrintFee):0f);
		//printFee.setChargeStatus(prePrintFee!=null && prePrintFee!=""?2:1);
		printFee.setChargeStatus(1);
		printFeeMapper.insert(printFee);
		
		PrintDetail  printDetail=new PrintDetail();
		printDetail.setPrintStatus(1);
		printDetail.setPrintId(print.getId());
		printDetail.setCheckStatus(1);
		
		PrintFeeDetail printFeeDetail=new PrintFeeDetail();
		printFeeDetail.setPrintFeeId(printFee.getId());
		
		if(applyPrintVo!=null){
			List<ApplyPrintDetail> applyPrintDetails=applyPrintVo.getApplyPrintList();
			if(applyPrintDetails!=null && applyPrintDetails.size()>0){
				for (ApplyPrintDetail applyPrintDetail : applyPrintDetails) {
					//申请打印详情
					applyPrintDetail.setApplyPrintId(applyPrint.getId());
					applyPrintDetail.setCheckStatus(1);
					applyPrintDetailMapper.insert(applyPrintDetail);
					
					//int applyPrintNum=getPerPrintPage(applyPrintDetail.getMedicalOnlyId(),applyPrintDetail.getPrintCopies(),applyPrint.getApplyReason());
					printDetail.setMedicalRecord(applyPrintDetail.getMedicalRecord());
					printDetail.setPrintCopies(applyPrintDetail.getPrintCopies());
					printDetail.setPatientName(applyPrintDetail.getPatientName());
					printDetail.setPatientCard(applyPrintDetail.getPatientCard());
					printDetail.setMedicalOnlyId(applyPrintDetail.getMedicalOnlyId());
					printDetail.setVersion(1);
					printDetailMapper.insert(printDetail);
					
					printFeeDetail.setMedicalRecord(applyPrintDetail.getMedicalRecord());
					printFeeDetail.setPatientName(applyPrintDetail.getPatientName());
					printFeeDetail.setPatientCard(applyPrintDetail.getPatientCard());
					printFeeDetail.setMedicalOnlyId(applyPrintDetail.getMedicalOnlyId());
					printFeeDetail.setPrintStatus(1);
					printFeeDetail.setCheckStatus(1);
					printFeeDetailMapper.insert(printFeeDetail);
				}
			}
		}
		
		return 1;
	}
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public HospitalNote addHospitalNote(String firstGuid) {
		HospitalNote hospitalNote = new HospitalNote();
		if (hospitalNoteMapper.isExistHospitalNote(firstGuid) > 0) {
			hospitalNote = hospitalNoteMapper.getHospitalNoteByFirstGuid(firstGuid);
			return hospitalNote;
		}
		Map<String, String> param = new HashMap<>();
		param.put("firstGuid", firstGuid);

		String userJson = HttpClientUtil.doPost(configProperties.getMedicalManage().getGetMedRecordByFirstGuidPath(),
				param);
		Result result = JsonUtils.jsonToPojo(userJson, Result.class);
		Map<String, Object> dataMap = (Map<String, Object>) result.getData();
		if (MapUtils.isNotEmpty(dataMap)) {
			hospitalNote.setFirstGuid(firstGuid);
			hospitalNote.setName(dataMap.get("NAME") == null ? null : (String) dataMap.get("NAME"));
			hospitalNote.setCreateDate(new Date());
			hospitalNote.setMrId(dataMap.get("mrId") == null ? null : (String) dataMap.get("mrId"));
			hospitalNote.setOnlyId(dataMap.get("onlyId") == null ? null : (String) dataMap.get("onlyId"));
			hospitalNote.setVisitNumber(dataMap.get("visit_number") == null?null:(Integer)dataMap.get("visit_number"));
			hospitalNote.setIdNumber(dataMap.get("idCard") == null ? null : (String) dataMap.get("idCard"));
			hospitalNote.setOutHospitalOfficeCode(
					dataMap.get("officeCode") == null ? null : (String) dataMap.get("officeCode"));
			hospitalNote.setOutHospitalOfficeName(
					dataMap.get("outOfficeName") == null ? null : (String) dataMap.get("outOfficeName"));
			hospitalNote.setOutHospitalTypeCode(
					dataMap.get("outHospitalTypeId") == null ? null : (Integer) dataMap.get("outHospitalTypeId") + "");
			hospitalNote.setOutHospitalType(
					dataMap.get("outHospitalType") == null ? null : (String) dataMap.get("outHospitalType"));
			hospitalNote.setBirthday(
					dataMap.get("birthday") == null ? null : DateUtil.strToDate((String) dataMap.get("birthday")));
			hospitalNote.setOutHospitalDate(dataMap.get("outHospitalDate") == null ? null
					: DateUtil.strToDate((String) dataMap.get("outHospitalDate")));
			hospitalNoteMapper.insert(hospitalNote);
		}

		return hospitalNote;
	}
	
	
	
	/**
	 * 查询申请的打印信息
	 * @return
	 */
	
	@Transactional(readOnly=true)
	public List<Map<String,Object>> queryApplyPrint(){
	     return	 applyPrintMapper.queryApplyPrint();
	 }
	
	/**
	 * 查询申请信息进行审核
	 * @param params
	 * @return
	 */
	
	@Transactional(readOnly=true)
	public List<Map<String,Object>> queryApplyToCheck(Params params){
		return applyPrintMapper.queryApplyCheck(params);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void addMailRegistartion(MailRegistraion mailRegistraion){
		mailRegistraion.setStatus(1);
		mailRegistraion.setCreateTime(new Date());
		mailRegistraion.setUpdateTime(new Date());
		mailRegistraionMapper.insertSelective(mailRegistraion);
	}
	
	/**
	 * 打印申请审核
	 * @param applyPrintDetailId
	 * @param status
	 * @param perCount
	 * @return
	 */
	
	@Transactional(propagation=Propagation.REQUIRED)
	public int updateApplyStatus(String applyPrintDetailId,String status,Integer perCount){
		
		String medRecord=null;
		//当拒批时预打印页数为0
		ApplyPrintDetail applyPrintDetail=applyPrintDetailMapper.selectByPrimaryKey(Integer.parseInt(applyPrintDetailId));
		
		applyPrintDetail.setId(Integer.parseInt(applyPrintDetailId));
		applyPrintDetail.setCheckTime(new Date());
		applyPrintDetail.setCheckStatus(Integer.parseInt(status));
		
		applyPrintDetailMapper.updateByPrimaryKeySelective(applyPrintDetail);
		//更新打印申请审核状态
		String uniqueId= applyPrintMapper.getUniqueidByApplyPrintDetailId(Integer.parseInt(applyPrintDetailId));
		medRecord=applyPrintDetail.getMedicalRecord();
		
		int printDetailId=printMapper.getPrintdetailIdByUniqueId(uniqueId, medRecord);
		PrintDetail printDetail=new PrintDetail();
		printDetail.setId(printDetailId);
		printDetail.setCheckStatus(Integer.parseInt(status));
		printDetailMapper.updateByPrimaryKeySelective(printDetail);

		
		int printFeeDetailId=printFeeMapper.getPrintFeeDetailIdByUnique(uniqueId, medRecord);
		PrintFeeDetail printFeeDetail=new PrintFeeDetail();
		printFeeDetail.setId(printFeeDetailId);
		printFeeDetail.setCheckStatus(Integer.parseInt(status));
		printFeeDetailMapper.updateByPrimaryKeySelective(printFeeDetail);
		System.out.println(uniqueId+"---"+medRecord+"--"+printDetailId+"--"+printFeeDetailId);
		
		
		//根据打印申请详情id获取查询条件
		//PrintSaoMiao printSaoMiao=applyPrintMapper.getSaoMiaoMsg(Integer.parseInt(applyPrintDetailId));
		
		//根据打印份数计算预计打印页数
		//perCount=perCount*printSaoMiao.getPrintCopies();
		
		//根据唯一标示查询Print
		//Print print=printMapper.getPrintByUniqueId(uniqueId);
		

		//print.setPrePrintPage(status.equals("2")?(print.getPrePrintPage()==null?perCount:(print.getPrePrintPage()+perCount)):(print.getPrePrintPage()==null?0:(print.getPrePrintPage()-perCount)));

		//printMapper.updateByPrimaryKeySelective(print);
		
		//根据唯一id和诊疗记录唯一标示查询打印详情信息
		/*PrintDetailExample printDetailExample=new PrintDetailExample();
		com.hutao.medical.pojo.print.PrintDetailExample.Criteria criteria=printDetailExample.createCriteria();
		criteria.andPrintIdEqualTo(print.getId());
		criteria.andMedicalOnlyIdEqualTo(printSaoMiao.getMedicalOnlyId());
		List<PrintDetail> printDetails=printDetailMapper.selectByExample(printDetailExample);
		
		//更新打印详情信息
		if(printDetails!=null && printDetails.size()>0){
			for (PrintDetail printDetail : printDetails) {
				printDetail.setPrePrintPage(status.equals("2")?perCount:0);
				printDetail.setCheckStatus(Integer.parseInt(status));
				printDetailMapper.updateByPrimaryKeySelective(printDetail);
			}
		}
		
		//根据uniqueId查询打印费用
		PrintFeeExample printFeeExample=new PrintFeeExample();
		com.hutao.medical.pojo.print.PrintFeeExample.Criteria printFeeCriteria= printFeeExample.createCriteria();
		printFeeCriteria.andUniqueIdEqualTo(printSaoMiao.getUniqueId());
		List<PrintFee> printFeeList=printFeeMapper.selectByExample(printFeeExample);
		
		if(printFeeList!=null && printFeeList.size()>0){
			for (PrintFee printFee : printFeeList) {
				printFee.setPrePrintPage(status.equals("2")?(printFee.getPrePrintPage()==null?perCount:(printFee.getPrePrintPage()+perCount)):(printFee.getPrePrintPage()==null?0:(printFee.getPrePrintPage()-perCount)));
				printFeeMapper.updateByPrimaryKeySelective(printFee);
				
				//根据打印费用id和诊疗记录唯一id查询打印费用详情信息
				PrintFeeDetailExample printFeeDetailExample=new PrintFeeDetailExample();
				com.hutao.medical.pojo.print.PrintFeeDetailExample.Criteria printFeeDetailCriteria=printFeeDetailExample.createCriteria();
				printFeeDetailCriteria.andPrintFeeIdEqualTo(printFee.getId());
				printFeeDetailCriteria.andMedicalOnlyIdEqualTo(printSaoMiao.getMedicalOnlyId());
				List<PrintFeeDetail> printFeeDetailList=printFeeDetailMapper.selectByExample(printFeeDetailExample);
				
				if(printFeeDetailList!=null && printFeeDetailList.size()>0){
					for (PrintFeeDetail printFeeDetail : printFeeDetailList) {
						printFeeDetail.setCheckStatus(Integer.parseInt(status));
						printFeeDetail.setPrePrintPage(status.equals("2")?perCount:0);
						printFeeDetailMapper.updateByPrimaryKeySelective(printFeeDetail);
					}
				}
				
				
			
			}*/
		//}
		
		
		
		
		return 1;
	}
	
	/**
	 * 批量更新审核状态
	 * @param applyPrintDetailIds
	 * @param status
	 * @return
	 */
	
	@Transactional(propagation=Propagation.REQUIRED)
	public String updateBatchApplyStatus(String applyPrintDetailIds,String status){
		
		if(StringUtil.isNotEmpty(applyPrintDetailIds)){
			ApplyPrintDetail applyPrintDetail=null;
			String[] applyPrintDetailArr=applyPrintDetailIds.split(",");
			
			for (String applyPrintDetailId : applyPrintDetailArr) {
				applyPrintDetail=new ApplyPrintDetail();
				applyPrintDetail.setId(Integer.parseInt(applyPrintDetailId));
				applyPrintDetail.setCheckTime(new Date());
				applyPrintDetail.setCheckStatus(Integer.parseInt(status));
			
				applyPrintDetailMapper.updateByPrimaryKeySelective(applyPrintDetail);
				
				applyPrintDetail=applyPrintDetailMapper.selectByPrimaryKey(Integer.parseInt(applyPrintDetailId));

				printDetailMapper.updateCheckStatusByMrIdAndCard(Integer.parseInt(status), applyPrintDetail.getPatientCard(), applyPrintDetail.getMedicalRecord());
			}
			return "success";
		}else{
			return "null";
		}
	}
	

	
	/**
	 * 获取打印信息
	 * @param params
	 * @return
	 */

	@Transactional(readOnly=true)
	public List<Map<String,Object>> getPrintList(Params params){
		
		return printMapper.getPrintList(params);
	}
	
	
	/**
	 * 获取打印数据数量
	 * @param params
	 * @return
	 */
	
	@Transactional(readOnly=true)
	public int getPrintCountbyParams(Params params){
		return printFeeMapper.getPrintCountbyParams(params);
	}
	
	/**
	 * 获取打印信息总数
	 * @param params
	 * @return
	 */
	
	@Transactional(readOnly=true)
	public int getPrintListCount(Params params){
		return printMapper.getPrintListCount(params);
	}
	
	
	/**
	 * 根据打印详情id获取详细信息
	 * @param printDetailId
	 * @return
	 */
	
	@Transactional(propagation=Propagation.REQUIRED)
	public PrintDetail getPrintDetail(Integer printDetailId){
		PrintDetail printDetail=printDetailMapper.selectByPrimaryKey(printDetailId);
		Print print=printMapper.selectByPrimaryKey(printDetail.getPrintId());
		if(printDetail!=null){		
			printDetail.setPrintCopies(print.getApplyReason());
			return printDetail;
		}else{
			return null;
		}
		
	}
	
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public String addPrintMsg(PrintDetail printDetail,String printCountFee){
		printDetail.setPrintStatus(2);
		printDetailMapper.updateByPrimaryKeySelective(printDetail);
		
		//查询print信息
		Print print=printMapper.selectByPrimaryKey(printDetail.getPrintId());
		Integer pageCount=0;
		pageCount=print.getPrintPagination()!=null?print.getPrintPagination():0;
		
	
		print.setPrintPagination(pageCount+printDetail.getPrintPagination());
		
		printMapper.updateByPrimaryKeySelective(print);
		PrintFeeExample  printFeeExample=new PrintFeeExample();
		com.hutao.medical.pojo.print.PrintFeeExample.Criteria  criteria= printFeeExample.createCriteria();
		criteria.andUniqueIdEqualTo(print.getUniqueId());
		List<PrintFee> printFeeList=printFeeMapper.selectByExample(printFeeExample);
		if(printFeeList!=null && printFeeList.size()>0){
			PrintFee printFee1=printFeeList.get(0);
			Integer pageSize=0;
			pageSize=printFee1.getPrintPagination()!=null?printFee1.getPrintPagination():0;
			printFee1.setPrintPagination(pageSize+printDetail.getPrintPagination());
			printFeeMapper.updateByPrimaryKeySelective(printFee1);
			
			Integer prntFeeDetailId=printFeeMapper.getPrintFeeDetailIdByUnique(print.getUniqueId(), printDetail.getMedicalRecord());
			
			PrintFeeDetail printFeeDetail=printFeeDetailMapper.selectByPrimaryKey(prntFeeDetailId);
			System.out.println(printCountFee);
			Float priceCount=Float.parseFloat(printCountFee);
			System.out.println(priceCount);
			printFeeDetail.setPrintCountPrice(priceCount);
			printFeeDetail.setPrintPagination(printDetail.getPrintPagination());
			printFeeDetail.setPrintStatus(2);
			printFeeDetailMapper.updateByPrimaryKeySelective(printFeeDetail);

		}

		return null;
	}
	
	
	@Transactional(readOnly=true)
	public int queryApplyCheckCount(Params params){
		return applyPrintMapper.queryApplyCheckCount(params);
	}
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public List<Map<String,Object>> getPrintFeeMsg(Params params){
		List<Map<String,Object>> printFeeMsgList=new ArrayList<>();
		List<Integer> printFeeIds=printFeeMapper.getPrintIdsbyParams(params);
		for (Integer printFeeId : printFeeIds) {
			printFeeMsgList.addAll(printFeeMapper.getPrintFeeMsg(printFeeId));
		}
		
		return printFeeMsgList;
	}
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public int updateChargeStatus(Integer printFeeId,Integer status){
		PrintFee printFee=new PrintFee();
		printFee.setId(printFeeId);
		printFee.setChargeStatus(status);
		printFee.setPerchargeCount(0f);
		return printFeeMapper.updateByPrimaryKeySelective(printFee);
	}
	
	public static String applyReason(int reason){
		
		switch(reason){
			case 1:
				return "医保";
			case 2:
				return "门规";
			default:
				return "其他";
		}
	}
	
	
	/**
	 * 根据申请详情id获取扫描查询相关信息
	 * @param applyPrintDetailId
	 * 			申请详情id
	 * @return
	 */
	
	@Transactional(readOnly=true)
	public PrintSaoMiao getSaoMiaoMsg(Integer applyPrintDetailId){
		return applyPrintMapper.getSaoMiaoMsg(applyPrintDetailId);
	}
	
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public int  updatePrinting(Integer printdetailId){
		PrintDetail printDetail=printDetailMapper.selectByPrimaryKey(printdetailId);
		if(printDetail!=null){
			printDetail.setVersion(printDetail.getVersion()+1);
			printDetail.setPrintStatus(3);
			return printDetailMapper.updateByPrimaryKeySelective(printDetail);
		}else{
			return 0;
		}
		
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public int addMedicalMail(MedicalMail medicalMail, String firstGuid, String operator) {
		MedicalFunction medicalFunction = new MedicalFunction();
		
		if (medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(firstGuid, FunctionType.mail) > 0) {
			medicalFunction = medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(firstGuid, FunctionType.mail);
		} else {
			medicalFunction.setCreateTime(new Date());
			medicalFunction.setFunctionTypeId(FunctionType.mail);
			medicalFunction.setFirstGuid(firstGuid);
			medicalFunction.setStatus(1);
			medicalFunctionMapper.insertSelective(medicalFunction);
		}
		
		//删除原来的记录
		medicalMailMapper.delete(medicalFunction.getId());
		medicalMail.setOperator(operator);
		medicalMail.setMedicalFunctionId(medicalFunction.getId());
		medicalMailMapper.insert(medicalMail);
		
		return 1;
	}
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	public int addPrintRecord(MedicalPrint medicalPrint,String firstGuid,String operator,String printApplyImageIds){
		MedicalFunction medicalFunction = new MedicalFunction();
		if(medicalFunctionMapper.isExistMedFunctionByFirstGuidAndFunType(firstGuid, FunctionType.print)>0){
			medicalFunction =medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(firstGuid, FunctionType.print);
		}else{
			medicalFunction.setCreateTime(new Date());
			medicalFunction.setFunctionTypeId(FunctionType.print);
			medicalFunction.setFirstGuid(firstGuid);
			medicalFunction.setStatus(1);
			medicalFunctionMapper.insertSelective(medicalFunction);
		}
		
		
		medicalPrint.setApplyTime(new Date());
		medicalPrint.setPrintTime(new Date());
		medicalPrint.setPrintMan(operator);
		medicalPrint.setMedicalFunctionId(medicalFunction.getId());
		medicalPrintMapper.insertSelective(medicalPrint);
		
		if(StringUtils.isNotEmpty(printApplyImageIds)){
			for (String  printApplyImagePath: printApplyImageIds.split(",")) {
				
				try {
					String sourcePath = printApplyImagePath;
					String printRegisterUploadPic = configProperties.getServer().getPrintRegisterUploadPic();
					printApplyImagePath = printApplyImagePath.substring(printApplyImagePath.lastIndexOf("/") + 1);
					
					String currentDateStr = DateUtil.dateFormat(new Date());
					
					File destFile = new File(printRegisterUploadPic + "/dest/" + currentDateStr);
					
					if  (!destFile.exists()) {
						destFile.mkdirs();
					}
					
					PrintApplyImage printApplyImage = new PrintApplyImage();
					printApplyImage.setFilePath("dest/" + currentDateStr + "/" + printApplyImagePath);
					printApplyImage.setCreateTime(new Date());
					printApplyImage.setMedicalPrintId(medicalPrint.getId());
					printApplyImageMapper.insert(printApplyImage);
					
					IOUtils.copy(new FileInputStream(printRegisterUploadPic + "/" + sourcePath), new FileOutputStream(
							new File(printRegisterUploadPic + "/dest/" + currentDateStr + "/" + printApplyImagePath)));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				
			}
		}
		
		/*if(StringUtils.isNotEmpty(printApplyImageIds)){
			for (String  printApplyImageId: printApplyImageIds.split(",")) {
				PrintApplyImage printApplyImage=printApplyImageMapper.selectByPrimaryKey(Integer.valueOf(printApplyImageId));
				if(printApplyImage!=null){
					printApplyImage.setMedicalPrintId(medicalPrint.getId());
					printApplyImage.setCreateTime(new Date());
					printApplyImageMapper.updateByPrimaryKeySelective(printApplyImage);
				}
			}
		}*/
		return 1;
	}
	
	
	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	public int addPrintMailRecord(PrintRecord printRecord,PrintMailRecord printMailRecord){
		printRecord.setStatus(1);
		printRecord.setPrintTime(new Date());
		printRecordMapper.insertSelective(printRecord);
		System.out.println(printRecord.getId());
		printMailRecord.setMailStatus(1);
		printMailRecord.setPrintRecordId(printRecord.getId());
		return printMailRecordMapper.insertSelective(printMailRecord);
	}
	

	   /**
     * 打印邮寄列表
     * @param printRecordVo
     * @return
     */
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public List<Map<String,Object>> getPrintMailDetailList(PrintRecordVo printRecordVo){
    	return printRecordMapper.getPrintMailDetailList(printRecordVo);
    }
	
	  /**
     * 导出邮寄详情到excel
     * @param printRecordVo
     * @return
     */
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public List<Map<String,Object>> exportMailListToExcel(PrintRecordVo printRecordVo){
		List<Map<String, Object>> listmap=printRecordMapper.exportMailListToExcel(printRecordVo);
		Map<String, Object> map=new HashMap<>();
		for (Map<String, Object> map1 : listmap) {
			map=map1;
			for (Entry<String, Object> map2 : map.entrySet()) {
				if(map2.getKey().equals("mailStatus")){
					if(map2.getValue().toString().equals("1")){
					map.put("mailStatus", "未邮寄");
					}else if(map2.getValue().toString().equals("2")){
					map.put("mailStatus", "已邮寄");
					}
				}
			}
		}
		
    	return listmap;
    }
    
    /**
     * 打印邮寄数量
     * @param printRecordVo
     * @return
     */
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public int getPrintMailDetaiCount(PrintRecordVo printRecordVo){
    	return printRecordMapper.getPrintMailDetaiCount(printRecordVo);
    }

	 //打印详情查询 
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public List<PrintRecord> selectByPrintRecordList(){
		return printRecordMapper.selectByPrintRecord();
	}

	@TargetDataSource(name="ds1")
	@Transactional(propagation=Propagation.REQUIRED)
	public int updatePrintMailRecordStatus(Integer printMailRecordId){
		PrintMailRecord printMailRecord =new PrintMailRecord();
		printMailRecord.setId(printMailRecordId);
		printMailRecord.setMailStatus(2);
		return	printMailRecordMapper.updateByPrimaryKeySelective(printMailRecord);
	}

	//打印详情信息数量 
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public int getPrintRecordCount(PrintRecordVo printRecordVo){
		return printRecordMapper.selectPrintRecordByCount(printRecordVo);
	}

	
	//打印详情条件查询 
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public List<PrintRecord> selectPrintRecordByConditionList(PrintRecordVo printRecordVo){
		return printRecordMapper.selectPrintRecordByCondition(printRecordVo);
	}
	
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
	public List<Map<String, Object>> exportPrintRecordToExcel(PrintRecordVo printRecordVo){
		List<Map<String, Object>> listmap=printRecordMapper.exportPrintRecordToExcel(printRecordVo);
		Map<String, Object> map=new HashMap<>();
		for (Map<String, Object> mapItem : listmap) {
			map=mapItem;
			for (Entry<String, Object> entry : map.entrySet()) {
				if(entry.getKey().equals("is_mail")){
					String mapkey=entry.getValue().toString();
					if(mapkey.equals("1")){
						map.put("is_mail", "否");
					}else if(mapkey.equals("2")){
						map.put("is_mail", "是");
					}
				}else if(map.containsKey("print_reason")){
					String mapkey=entry.getValue().toString();
					if(mapkey.equals("1")){
						map.put("print_reason", "门规");
					}else if(mapkey.equals("2")){
						map.put("print_reason", "医保");
					}else if(mapkey.equals("3")){
						map.put("print_reason", "其他");
					}
				}
			}
		}
		return listmap;
	}
	
	public String verificationEmail(String valueid){
		if(valueid.equals("1")){
			return "否";
		}else{
			return "是";
		}
		
	}
	
    /**
     * 统计打印工作量
     * @param printRecordVo
     * @return
     */
	@TargetDataSource(name="ds1")
	@Transactional(readOnly=true)
    public List<Map<String,Object>> getPrintWorkTotal(PrintRecordVo printRecordVo){
    	return printRecordMapper.getPrintWorkTotal(printRecordVo);
    }
	
	/**
	 * 查询打印详情信息
	 * @param printRecordVo
	 * @return
	 */
	@Transactional(readOnly=true)
	public Map<String,Object> getMedicalPrintDetail(PrintRecordVo printRecordVo){
		Map<String,Object> map = new HashMap<>();
		List<Map<String,Object>> printList = medicalPrintMapper.getMedicalPrintDetail(printRecordVo);
		int printCount = medicalPrintMapper.getMedicalPrintDetailCount(printRecordVo);
		map.put("printList", printList);
		map.put("totalCount", printCount);
		return map;
	}



	@Transactional(propagation=Propagation.REQUIRED)
	public PrintApplyImage addMedicalPrintImage(PrintApplyImage printApplyImage) {
		printApplyImageMapper.insertSelective(printApplyImage);
		return printApplyImage;
	}
	
	@Transactional(readOnly=true)
	 public List<Map<String,Object>> getPrintRecordDetail(Integer medicalPrintId){
		 return medicalPrintMapper.getPrintRecordDetail(medicalPrintId);
	 }
	    
	@Transactional(readOnly=true)
	 public List<Map<String,Object>> getPrintRecordImg(Integer medicalPrintId){
		return medicalPrintMapper.getPrintRecordImg(medicalPrintId);
	}
	
	
	
	
	public List<Integer> getPrintPageByPrintType(String printTypeId){
		List<Integer> list = new ArrayList<>();
		Map<String,String> params = new HashMap<>();
		params.put("printTypeId", printTypeId);
		String printJson = HttpClientUtil.doGet(configProperties.getMedicalManage().getPrintPageByPrintType(), params);
		System.out.println(printJson);
		Result result = JSONObject.parseObject(printJson, Result.class);
		if(result.isSuccess()){
			list=(List<Integer>) result.getData();
		}
		return list;
	}



	
	
	public List<PrintPageDto> getScanImg(String visitGuid, String applyReason) throws IOException, InterruptedException, IM4JavaException {
		Map<String,String> params=new HashMap<>();
		List<PrintPageDto> printPageDtoList = new ArrayList<>();
		params.put("firstGuid", visitGuid);
		params.put("printerType", applyReason);
		String userJson = HttpClientUtil.doGet(configProperties.getMedicalManage().getPicSourcePath(), params);
		Result result = JSONObject.parseObject(userJson, Result.class);
		if(result!=null){
			@SuppressWarnings("unchecked")
			Map<String, Object> mapObj = (Map<String, Object>) result.getData();
			@SuppressWarnings("unchecked")
			List<Map<String,Object>> mapList=(List<Map<String, Object>>) mapObj.get("printerImages");
			PrintPageDto printPageDto = null;
			for (Map<String, Object> map : mapList) {
				printPageDto = new PrintPageDto();
				//{"pageTypeName":"入院记录","printerTypeId":5,"fileName":"njuc63kbki1o7wj088w0x912x4b9p09y3v1pn5csc8z9uykfbvcrudokkeeu3m68sjnh51crclaelb86hzjetfptgon000yqs.png","imageUrl":"http://localhost:8090/upload/4z/0v/j1/rp/njuc63kbki1o7wj088w0x912x4b9p09y3v1pn5csc8z9uykfbvcrudokkeeu3m68sjnh51crclaelb86hzjetfptgon000yqs.png","fileUrl":"4z/0v/j1/rp/","hostUrl":"http://localhost:8090/upload/"}
				String fileUrl=(String)map.get("fileUrl");
				String fileName=(String)map.get("fileName");
				if(map.get("printerTypeId")==null){
					continue;
				}
				
				if(map.get("createDate")!=null){					
					try {
						printPageDto.setCreateDate(DateUtil.dateParse("yyyy-MM-dd HH:mm:ss", (String)map.get("createDate")));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				printPageDto.setPrintPageType((Integer)map.get("printerTypeId"));
				if(StringUtils.isEmpty(fileUrl) || StringUtils.isEmpty(fileName)){
					continue;
				}
				String imagePath = configProperties.getServer().getPicHostFileDir()+fileUrl+fileName;
				printPageDto.setPrintImagePath(imagePath);
				printPageDtoList.add(printPageDto);
				
			}
		}
		return printPageDtoList;
	}
	
	public List<PrintPageDto> rotateImgAngle(List<PrintPageDto> printPageDtoList){
		List<PrintPageDto> rotateImgList = new ArrayList<>();
		for (PrintPageDto printPageDto : printPageDtoList) {
			String img =printPageDto.getPrintImagePath();
			int length =img.lastIndexOf("/");
			String imgPath=img.substring(0,length+1);
			String fileName = img.substring(length+1, img.length());
			String newPath=imgPath+"temp/"+fileName;
			TmFileUtil.createFloder(imgPath+"temp/");
			File markPicTempFile = new File(newPath);
			if(markPicTempFile.exists()){
				//rotateImgList.add(newPath);
				printPageDto.setPrintImagePath(newPath);
				rotateImgList.add(printPageDto);
			}else{
				try {
					GraphicsMagicUtil.rotate(img, newPath,90);
					//rotateImgList.add(newPath);
					printPageDto.setPrintImagePath(newPath);
					rotateImgList.add(printPageDto);
				} catch (Exception e) {
					e.printStackTrace();
				} 
			}
		}
		return rotateImgList;
	}
	
	
	public List<PrintPageDto> imageWaterMark(List<PrintPageDto> printPageDtoList){
		List<PrintPageDto> printMarkImgList = new ArrayList<>();
		for (PrintPageDto printPageDto : printPageDtoList) {
			String img= printPageDto.getPrintImagePath();
			int length =img.lastIndexOf("/");
			String fileName = img.substring(length+1, img.length());
			// 没有文件夹创建文件夹
			TmFileUtil.createFloder(configProperties.getServer().getPrintMarkImgFileDir());
			File markPicTempFile = new File(configProperties.getServer().getPrintMarkImgFileDir()+fileName);

			if (markPicTempFile.exists()) {
				//printMarkImgList.add(configProperties.getServer().getPrintMarkImgPath()+fileName);
				printPageDto.setPrintImagePath(configProperties.getServer().getPrintMarkImgPath()+fileName);
				printMarkImgList.add(printPageDto);
			}else{
				int width= GraphicsMagicUtil.getWidth(img);
				int height=GraphicsMagicUtil.getHeight(img);
				int startX=(width-500)/2;
				int startY=(height-500)/2;
				try {
					GraphicsMagicUtil.addWatermarkToImg(img, configProperties.getServer().getPrintMarkImgFileDir()+fileName, configProperties.getServer().getLogoPath(), 500, 500,
							startX, startY, 20);
					//printMarkImgList.add(configProperties.getServer().getPrintMarkImgPath()+fileName);
					printPageDto.setPrintImagePath(configProperties.getServer().getPrintMarkImgPath()+fileName);
					printMarkImgList.add(printPageDto);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (IM4JavaException e) {
					e.printStackTrace();
				}
				
			}
			
		}
		
		return printMarkImgList;
		
	}
	
	
	public List<PrintPageDto> getPrintMarkImg(String visitGuid, String applyReason) throws IOException, InterruptedException, IM4JavaException {
		Map<String,String> params=new HashMap<>();
		List<PrintPageDto> printPageDtoList = new ArrayList<>();
		params.put("firstGuid", visitGuid);
		params.put("printerType", applyReason);
		List<String> printMarkImgList = new ArrayList<>();
		String userJson = HttpClientUtil.doGet(configProperties.getMedicalManage().getPicSourcePath(), params);
		Result result = JSONObject.parseObject(userJson, Result.class);
		
		if(result!=null){
			Map<String, Object> mapObj = (Map<String, Object>) result.getData();
			List<Map<String,Object>> mapList=(List<Map<String, Object>>) mapObj.get("printerImages");
			
			PrintPageDto printPageDto = null;
			for (Map<String, Object> map : mapList) {
				printPageDto = new PrintPageDto();
				String fileUrl=(String)map.get("fileUrl");
				String fileName=(String)map.get("fileName");
				String imageUrl=(String)map.get("imageUrl");
				
				if(map.get("printerTypeId")==null){
					continue;
				}
				if(map.get("originalName")!=null){
					printPageDto.setOriginalName((String)map.get("originalName"));
				}
				
				if(map.get("createDate")!=null){					
					try {
						printPageDto.setCreateDate(DateUtil.dateParse("yyyy-MM-dd HH:mm:ss", (String)map.get("createDate")));
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				
				printPageDto.setPrintPageType((Integer)map.get("printerTypeId"));
				
				if(StringUtils.isEmpty(fileUrl) || StringUtils.isEmpty(fileName)){
					continue;
				}
				
				printPageDto.setPrintImagePath(imageUrl);
				printPageDtoList.add(printPageDto);
				
		}
		}
		return printPageDtoList;
	}

	@Transactional(readOnly=true)
	public int selectPrintNumByGuid(String firstGuid) {
	    return medicalPrintMapper.selectPrintNumByGuid(firstGuid);
	}
	
	
	@Transactional(readOnly=true)
	public Map<String,Object> selectPrintCheckByGuid(String firstGuid) {
	    return medicalPrintMapper.selectCheckStatusByGuid(firstGuid,FunctionType.print);
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public int printCheckByGuid(String firstGuid) {
		MedicalFunction function = medicalFunctionMapper.getMediFunctionByFirstGuidAndFunType(firstGuid, FunctionType.print);
		if(function==null) {
			function = new MedicalFunction();
			function.setCreateTime(new Date());
			function.setFirstGuid(firstGuid);
			function.setStatus(2);
			function.setFunctionTypeId( FunctionType.print);
			return medicalFunctionMapper.insertSelective(function);
		}else {
			function.setStatus(2);
			function.setCreateTime(new Date());
			return medicalFunctionMapper.updateByPrimaryKeySelective(function);
		}
	}
	
	@Transactional(readOnly=true)
	public Map<String,Object> selectMedPrintCheck(PrintCheckVo printCheckVo){
		Map<String,Object> map = new HashMap<>();
		List<Map<String,Object>> noteList = hospitalNoteMapper.selectMedRecordCheck(printCheckVo);
		int count = hospitalNoteMapper.selectMedRecordCheckCount(printCheckVo);
		map.put("noteList", noteList);
		map.put("count", count);
		return map;
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public void updateCheckStatus(Integer funId) {
		MedicalFunction function = medicalFunctionMapper.selectByPrimaryKey(funId);
		function.setCreateTime(new Date());
		function.setStatus(1);
		medicalFunctionMapper.updateByPrimaryKeySelective(function);
		
	}
	
	
	
	
	
}
